package com.itbaima.csmall.cart.webapi.kafka;

import com.google.gson.Gson;
import com.itbaima.csmall.commons.pojo.cart.entity.Cart;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * <p>Producer</p>
 *
 * @author Chen
 * @since 2023/3/8 10:32:32
 */
@Slf4j
@Component
public class Producer {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;

    public static final String TOPIC_KEY = "myCart";
    int i = 1;

    @Scheduled(cron = "0/8 * * * * ?")
    public void sendMessage() {
        Cart cart = new Cart();
        cart.setId(i++);
        cart.setUserId("UU100");
        cart.setCommodityCode("PC100");
        cart.setCount(1 + RandomUtils.nextInt(10));
        cart.setPrice(10 + RandomUtils.nextInt(90));
        Gson gson = new Gson();
        String json = gson.toJson(cart);
        log.info("==>发送的消息：{}", json);
        kafkaTemplate.send(TOPIC_KEY, json);
        amqpTemplate.convertAndSend(TOPIC_KEY, json);
    }

    @Bean
    public Queue queue() {
        return new Queue(TOPIC_KEY, false, false, false, null);
    }

}
